package day02;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JdbcUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/remove")
public class RemoveEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("RemoveEmpServlet.service");

        Integer id=Integer.parseInt(request.getParameter("id"));

        System.out.println("id = " + id);

        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("delete from t_emp ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setInt(1,id);

            ps.executeUpdate();


            con.commit();

            response.sendRedirect(request.getContextPath()+"/list");
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }
    }
}
